/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.cslg.dorm.service;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.cslg.dorm.entity.DormBuilding;
import com.thinkgem.jeesite.cslg.dorm.dao.DormBuildingDao;
import com.thinkgem.jeesite.cslg.dorm.entity.DormRoom;
import com.thinkgem.jeesite.cslg.dorm.dao.DormRoomDao;

/**
 * 宿舍楼Service
 * @author 张文锦
 * @version 2017-02-11
 */
@Service
@Transactional(readOnly = true)
public class DormBuildingService extends CrudService<DormBuildingDao, DormBuilding> {

	@Autowired
	private DormRoomDao dormRoomDao;
	
	public DormBuilding get(String id) {
		DormBuilding dormBuilding = super.get(id);
		dormBuilding.setDormRoomList(dormRoomDao.findList(new DormRoom(dormBuilding)));
		return dormBuilding;
	}
	
	public List<DormBuilding> findList(DormBuilding dormBuilding) {
		return super.findList(dormBuilding);
	}
	
	public Page<DormBuilding> findPage(Page<DormBuilding> page, DormBuilding dormBuilding) {
		return super.findPage(page, dormBuilding);
	}
	
	@Transactional(readOnly = false)
	public void save(DormBuilding dormBuilding) {
		super.save(dormBuilding);
		for(int floor=1;floor<=dormBuilding.getFloorNum();floor++){
            for(int room=1;room<=dormBuilding.getRoomNum();room++){
            	DormRoom d=new DormRoom();
            	d.setIsfull("0");
            	d.setMaxStuNumb(""+dormBuilding.getMaxStuNumb());
            	d.setNowStuNumb("0");
            	d.setSsh(dormBuilding.getLh()+floor+String.format("%02d",room));
            	d.setDelFlag(DormRoom.DEL_FLAG_NORMAL);
            	dormBuilding.getDormRoomList().add(d);
            }
		}
		for (DormRoom dormRoom : dormBuilding.getDormRoomList()){
			System.out.println(dormRoom.getSsh());
//			if (dormRoom.getId() == null){
//				dormRoom.setId(IdGen.uuid());
//			}
			if (DormRoom.DEL_FLAG_NORMAL.equals(dormRoom.getDelFlag())){
				if (StringUtils.isBlank(dormRoom.getId())){
					dormRoom.setDormBuilding(dormBuilding);
					dormRoom.preInsert();
					dormRoomDao.insert(dormRoom);
				}else{
					dormRoom.preUpdate();
					dormRoomDao.update(dormRoom);
				}
			}else{
				dormRoomDao.delete(dormRoom);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(DormBuilding dormBuilding) {
		super.delete(dormBuilding);
		dormRoomDao.delete(new DormRoom(dormBuilding));
	}
	
}